package com.example.test.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.example.test.entity.AreaDemo;
import com.example.test.entity.BasicAdministrativeDivision;
import com.example.test.service.IAreaDemoService;
import com.example.test.service.IBasicAdministrativeDivisionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 牧羊人
 * @since 2022-03-24
 */
@RestController
@RequestMapping("/area-demo")
public class AreaDemoController {

    @Autowired
    IAreaDemoService areaDemoService;

    @Autowired
    IBasicAdministrativeDivisionService basicAdministrativeDivisionService;


//    @PostConstruct
    public void ss() {
        List<AreaDemo> list = areaDemoService.list();
        // sheng
        List<AreaDemo> shengList = list.stream().filter(areaDemo -> areaDemo.getCode().contains("0000")).collect(Collectors.toList());
        System.out.println("省: " + shengList.size());

        String zhixia = "北京市,天津市,上海市,重庆市";

        List<String> strings = CollectionUtil.newArrayList(zhixia.split(","));
        List<AreaDemo> zhixiaList = shengList.stream().filter(demo -> strings.contains(demo.getName())).collect(Collectors.toList());

        List<BasicAdministrativeDivision> result = new ArrayList<>();
        for (AreaDemo areaDemo : zhixiaList) {
            String substring = areaDemo.getCode().substring(0, 3);
            AtomicInteger i = new AtomicInteger();
            BasicAdministrativeDivision erji = new BasicAdministrativeDivision();
            erji.setCode(areaDemo.getCode().substring(0, 3) + "100");
            erji.setName(areaDemo.getName());
            erji.setLevel(2);
            erji.setParentCode(areaDemo.getCode());
            erji.setSort(i.get());
            result.add(erji);
            for (AreaDemo areaDemo1 : list) {
                i.getAndIncrement();
                if (areaDemo1.getCode().startsWith(substring) && !areaDemo1.getCode().endsWith("00")) {
                    BasicAdministrativeDivision basicAdministrativeDivision = new BasicAdministrativeDivision();
                    basicAdministrativeDivision.setCode(areaDemo1.getCode());
                    basicAdministrativeDivision.setName(areaDemo1.getName());
                    basicAdministrativeDivision.setLevel(3);
                    basicAdministrativeDivision.setParentCode(erji.getCode());
                    basicAdministrativeDivision.setSort(i.get());
                    result.add(basicAdministrativeDivision);
                }
            }
        }
        basicAdministrativeDivisionService.saveBatch(result, result.size());
    }

}
